package goods

import (
	"context"
	"errors"
	"gitee.com/enjoy_5/goods-rpc/internal/server"
	"gitee.com/enjoy_5/goods-rpc/proto/goods"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type HandlerGoods struct {
	goods.UnimplementedGoodsServer
}

func (h *HandlerGoods) GetGoodInfo(ctx context.Context, req *goods.GetGoodInfoRequest) (*goods.GetGoodInfoResponse, error) {
	if req.ID == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "ID is required")
	}

	info, err := server.GetGoodsInfo(req.ID)
	if err != nil {
		return nil, errors.New("goodsId not found")
	}
	return &goods.GetGoodInfoResponse{
		Info: info,
	}, nil
}

func (h *HandlerGoods) GetSkuInfoByPropertyValueIDs(ctx context.Context, req *goods.GetSkuInfoByPropertyValueIDsRequest) (*goods.GetSkuInfoByPropertyValueIDsResponse, error) {
	info, err := server.GetGoodsPriceByPropertyId(req.PropertyValueId1, req.PropertyValueId2, req.PropertyValueId3)
	if err != nil {
		return nil, errors.New("PropertyValueId not found")
	}
	return &goods.GetSkuInfoByPropertyValueIDsResponse{
		Info: info,
	}, nil
}

func (h *HandlerGoods) SearchGoodsByTitle(ctx context.Context, req *goods.SearchGoodsByTitleRequest) (*goods.SearchGoodsByTitleResponse, error) {
	if req.Title == "" {
		return nil, status.Errorf(codes.InvalidArgument, "Title is required")
	}
	info, err := server.SearchGoodsByTitle(req.Title, int(req.Page), int(req.PageSize))
	if err != nil {
		return nil, err
	}
	return &goods.SearchGoodsByTitleResponse{
		Info: info,
	}, nil
}

// *
func (h *HandlerGoods) GetGoodsList(ctx context.Context, req *goods.GetGoodsListBySkuIDReq) (*goods.GetGoodsListBySkuIDResp, error) {
	info, err := server.GetGoodsInfoBySkuIds(req.GetSkuID())
	if err != nil {
		return nil, err
	}
	return &goods.GetGoodsListBySkuIDResp{Info: info}, nil
}

func (h *HandlerGoods) GetSkuInfoByID(ctx context.Context, req *goods.GetSkuInfoByIDRequest) (*goods.GetSkuInfoByIDResponse, error) {
	if req.SkuID == 0 {
		return nil, status.Errorf(codes.InvalidArgument, "SkuID is required")
	}
	id, err := server.GetSkuInfoByID(req.SkuID)
	if err != nil {
		return nil, err
	}
	return &goods.GetSkuInfoByIDResponse{Info: id}, nil
}

func (h *HandlerGoods) GoodList(ctx context.Context, req *goods.GoodListRequest) (resp *goods.GoodListResponse, err error) {
	list, err := server.GoodList(int(req.Page), int(req.PageSize), req.TypeID, req.Title)
	if err != nil {
		return nil, status.Errorf(codes.Unimplemented, "method GoodList not implemented")
	}
	return &goods.GoodListResponse{In: list}, nil
}
